package com.asia5b.a5mall.member.fragment

import android.view.View
import android.view.ViewGroup
import androidx.core.widget.NestedScrollView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5bmall.resource.ResString
import com.asia5b.a5mall.member.R
import com.asia5b.a5mall.member.adapter.MineGuessAdapter
import com.asia5b.a5mall.member.adapter.MineItemAdapter
import com.asia5b.a5mall.member.databinding.FragmentMineBinding
import com.asia5b.a5mall.middleware.base.SimpleFragment
import com.asia5b.a5mall.middleware.config.Asia5bPayUtils
import com.asia5b.a5mall.middleware.config.CountrysRepository
import com.asia5b.a5mall.middleware.config.UserRepository
import com.asia5b.a5mall.middleware.event.LoginEvent
import com.asia5b.a5mall.middleware.event.LogoutEvent
import com.asia5b.a5mall.middleware.logic.viewmodel.member.MineFragmentVM
import com.asia5b.a5mall.middleware.model.bean.MineItemBean
import com.asia5b.a5mall.middleware.model.bean.OrderListType
import com.asia5b.a5mall.middleware.model.member.MemberCountModel
import com.asia5b.a5mall.middleware.model.shop.AbsGoodsModel
import com.asia5b.a5mall.middleware.utils.*
import com.luck.picture.lib.decoration.GridSpacingItemDecoration
import com.scwang.smartrefresh.layout.api.RefreshLayout
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.fragment_mine.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by zhangyuncai on 2019/12/20.
 */
@Route(path = ActCons.MineFragment)
class MineFragment : SimpleFragment<MineFragmentVM, FragmentMineBinding>() {

    override val viewModelClazz: Class<MineFragmentVM>
        get() = MineFragmentVM::class.java

    override fun getDataBinding(container: ViewGroup?): FragmentMineBinding {
        return FragmentMineBinding.inflate(layoutInflater, container, false)
    }

    private var memberCountModel: MemberCountModel? = null
    private val mGuessDatas = arrayListOf<AbsGoodsModel>()
    private val mineGuessAdapter by lazy {
        MineGuessAdapter(mGuessDatas)
    }


    override fun lazyFetchData() {
        getGuessLike(0)
    }


    override fun initView() {
        mSmartRefreshLayout = mDataBinding.autoMine
//        CountrysRepository.update()
        UserRepository.updateUserInfo()
        UserRepository.getUserInfoOB()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    setUserInfoView()
                }.joinComposite(mCompositeDisposable)
        UserRepository.updateInboxCount()
        UserRepository.getInboxOB()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    memberCountModel = it
                    setMemberOtherInfo(it)
                    setMyOrdersView()
                }.joinComposite(mCompositeDisposable)
        setUserInfoView()
        setMyOrdersView()
//        setInterOrdersView()
        setCustomerView()

        val gridSpacingItemDecoration = GridSpacingItemDecoration(2, DisplayUtils.dip2px(requireContext(), 5f), false)
        rl_mine_guess.run {
            addItemDecoration(gridSpacingItemDecoration)
            layoutManager = GridLayoutManager(requireContext(), 2)
            adapter = mineGuessAdapter
        }

    }

    private fun setMemberOtherInfo(memberCountModel: MemberCountModel) {
        memberCountModel.run {
            tv_mine_attentiongoods.text = "$goods_collect_count"
            tv_mine_attentionshop.text = "$shop_collect_count"
            tv_mine_coupon.text = "$coupon_collect_count"
            tv_mine_footrecords.text = "$history_collect_count"
            UserRepository.setNums(tv_mine_msg_count, unread_message_count)
        }
    }

    /**
     * 设置用户信息
     */
    private fun setUserInfoView() {
        if (!UserRepository.isLogin()) {
            iv_mine_head.setImageResource(R.drawable.head_default)
            tv_mine_name.text=String.format("%s/%s",getString(R.string.登录),getString(R.string.注册))
            tv_mine_point.text = getString(R.string.等级积分_数, "0")
            tv_mine_point.visibility = View.GONE
        } else {
            val info = UserRepository.getUserInfo()
            info.then { model ->
                WImageLoader.displayImage(model.face, iv_mine_head, R.drawable.head_default)
                tv_mine_name.text = model.nikename
                val point = "${model.buyPoint}"
                tv_mine_point.text = getString(R.string.等级积分_数, point)
                tv_mine_point.visibility = View.VISIBLE
            }
        }
    }


    /**
     * 设置我的订单
     */
    private fun setMyOrdersView() {
        val list = arrayListOf<MineItemBean>()
        /*待付款*/
        list.add(MineItemBean(R.drawable.ic_mine_pay1, getString(R.string.待付款), View.OnClickListener {
            push(ActCons.OrderListActivity, {
                it.withSerializable("type", OrderListType.WAIT_PAY)
            }, isNeedLogin = true)
        }))
        /*待收货*/
//        list.add(MineItemBean(R.drawable.ic_mine_receive, getString(R.string.memberfragment_receivewait), View.OnClickListener {
//            push(ActCons.OrderListActivity, {
//                it.withInt("state", DataBindingAction.ORDER_WAIT_ROG)
//            }, isNeedLogin = !UserRepository.isLogin())
//        }))
        /*申请打包*/
        list.add(MineItemBean(R.drawable.ic_mine_applypack, getString(R.string.申请打包), View.OnClickListener {
            push(ActCons.OrderListActivity, {
                it.withSerializable("type", OrderListType.APPLY_PACKAGING)
            }, isNeedLogin = true)
        }))
        /*待评论*/
//        list.add(MineItemBean(R.drawable.ic_mine_commens, getString(R.string.memberfragment_commenswait), View.OnClickListener {
//            push(ActCons.CommentListActivity, isNeedLogin = !UserRepository.isLogin())
//        }))
        /*补差价*/
        val diffBean = MineItemBean(R.drawable.ic_mine_commens, getString(R.string.补差价), View.OnClickListener {
            push(ActCons.OrderListActivity, {
                it.withSerializable("type", OrderListType.PAY_DIFF)
            }, isNeedLogin = true)
        })
        diffBean.other = memberCountModel?.pay_diff_count ?: 0
        list.add(diffBean)
        /*退换/售后*/
        list.add(MineItemBean(R.drawable.ic_mine_changegoods, getString(R.string.退换_售后), View.OnClickListener {
//            push(ActCons.AftersaleListActivity, isNeedLogin = !UserRepository.isLogin())
            push(ActCons.OrderListActivity, {
                it.withSerializable("type", OrderListType.WAIT_REFUND)
            }, isNeedLogin = true)
        }))
        /*我的订单*/
        list.add(MineItemBean(R.drawable.ic_mine_myorder, getString(R.string.我的订单), View.OnClickListener {
            push(ActCons.OrderListActivity, {
                it.withSerializable("type", OrderListType.ALL)
            }, isNeedLogin = true)

        }))
        rl_mine_myorder.run {
            layoutManager = GridLayoutManager(requireContext(), list.size)
            adapter = MineItemAdapter(list)
        }
    }

    /**
     * 设置国际订单
     */
//    fun setInterOrdersView() {
//        val list = arrayListOf<MineItemBean>()
//        list.add(MineItemBean(R.drawable.ic_mine_pay2, getString(R.string.待付款), View.OnClickListener {
//            if (UserRepository.isLogin(mActivity)) {
//
//            }
//        }))
//        list.add(MineItemBean(R.drawable.ic_mine_package, getString(R.string.待打包), View.OnClickListener {
//            if (UserRepository.isLogin(mActivity)) {
//
//            }
//        }))
//        list.add(MineItemBean(R.drawable.ic_mine_rucang, getString(R.string.已入仓), View.OnClickListener {
//            if (UserRepository.isLogin(mActivity)) {
//
//            }
//        }))
//        list.add(MineItemBean(R.drawable.ic_mine_weirucang, getString(R.string.未入仓), View.OnClickListener {
//            if (UserRepository.isLogin(mActivity)) {
//
//            }
//        }))
//        list.add(MineItemBean(R.drawable.ic_mine_interorder, getString(R.string.国际订单), View.OnClickListener {
//            if (UserRepository.isLogin(mActivity)) {
//
//            }
//        }))
//        rl_mine_interorder.run {
//            layoutManager = GridLayoutManager(requireContext(), list.size)
//            adapter = MineItemAdapter(list)
//        }
//    }

    /**
     * 设置我的服务
     */
    private fun setCustomerView() {
        val list = arrayListOf<MineItemBean>()
        /*TODO 我的钱包到支付app*/
//        list.add(MineItemBean(R.drawable.ic_mine_mypurse, getString(R.string.memberfragment_mypurse), View.OnClickListener {
//            if (UserRepository.isLogin(mActivity)) {
//                Asia5bPayUtils.skipAsiaPayHome(mActivity ,1)
//            }
//        }))
//        list.add(MineItemBean(R.drawable.ic_mine_fenxiao, getString(R.string.memberfragment_fenxiao), View.OnClickListener {
//            push(ActCons.SaleManaActivity, isNeedLogin = !UserRepository.isLogin())
//        }))
        //todo 暂时不做
//        list.add(MineItemBean(R.drawable.ic_mine_fapiao, getString(R.string.memberfragment_fapiao), View.OnClickListener {
//            if (UserRepository.isLogin(mActivity)) {
//
//            }
//        }))
//        list.add(MineItemBean(R.drawable.ic_mine_customer, getString(R.string.memberfragment_kefu), View.OnClickListener {
//            CancelSureDialog(requireContext(), R.string.memberfragment_customer_content, WCallBack<Boolean> { }).show()
//        }))
//        list.add(MineItemBean(R.drawable.ic_mine_zixun, getString(R.string.memberfragment_zixun), View.OnClickListener {
//            //todo 老朱说没这个界面了
//            push(ActCons.AskActivity, isNeedLogin = !UserRepository.isLogin())
//        }))

        /*TODO 交易记录到支付app*/
//        list.add(MineItemBean(R.drawable.ic_mine_jiaoyi, getString(R.string.memberfragment_jiaoyijilu), View.OnClickListener {
//            if (UserRepository.isLogin(mActivity)) {
//                Asia5bPayUtils.skipAsiaPayBill(mActivity )
//            }
//        }))
        /*TODO 余额明细到支付app*/
        list.add(MineItemBean(R.drawable.ic_mine_yuemingxi, getString(R.string.我的钱包), View.OnClickListener {
            if (UserRepository.isLogin(mActivity)) {
                Asia5bPayUtils.skipAsiaPayHome2(mActivity)
            }
        }))
        /*TODO 账户充值*/
        list.add(MineItemBean(R.drawable.ic_mine_zhanghuchongzhi, getString(R.string.账户充值), View.OnClickListener {
            if (UserRepository.isLogin(mActivity)) {
                Asia5bPayUtils.skipPayTopup(mActivity)
            }
        }))
        /*TODO 账户取现*/
        list.add(MineItemBean(R.drawable.ic_mine_zhanghuquxian, getString(R.string.账户取现), View.OnClickListener {
            if (UserRepository.isLogin(mActivity)) {
                Asia5bPayUtils.skipAsiaPayHome(mActivity, 1)
            }
        }))
        //TODO 我的评价
        list.add(MineItemBean(R.drawable.ic_mine_wodepingjia, getString(R.string.我的评价), View.OnClickListener {
            push(ActCons.CommentListActivity, isNeedLogin = true)
        }))
        rl_mine_customer.run {
            layoutManager = GridLayoutManager(requireContext(), 4)
            adapter = MineItemAdapter(list)
        }
    }


    override fun initEvent() {
        //个人头像
        cons_mine_info_vessel.setOnClickListener {
            push(ActCons.PersonInfoActivity, isNeedLogin = true)
        }
        nsv_mine_vessl.setOnScrollChangeListener { _: NestedScrollView?, _: Int, t: Int, _: Int, _: Int ->
            //本来的背景色:#00A7FA
            var alpha = t / (DisplayUtils.dip2px(mActivity, 100f) * 1.0f)
            if (alpha < 0) {
                alpha = 0.0f
            } else if (alpha > 1) {
                alpha = 1f
            }
            view_mine_scan_vessel_bg.alpha = alpha
        }
        //扫一扫
        iv_mine_scan.setOnClickListener {
            push(ActCons.ScanActivity)
        }
        //消息
        iv_mine_message.setOnClickListener {
            push(ActCons.MessageActivity, isNeedLogin = true)
        }
        //设置
        iv_mine_setting.setOnClickListener {
            push(ActCons.SettingActivity)
        }
        //等级积分
        tv_mine_point.setOnClickListener {
            push(ActCons.PointListActivity, {
                it.withString("title", ResString.get(R.string.积分明细))
            }, isNeedLogin = true)
        }
        //商品关注
        ll_mine_attentiongoods.setOnClickListener {
            push(ActCons.CollectActivity, {
                it.withInt("type", 0)
            }, isNeedLogin = true)
        }
        //店铺关注
        ll_mine_attentionshop.setOnClickListener {
            push(ActCons.CollectActivity, {
                it.withInt("type", 1)
            }, isNeedLogin = true)
        }
        //优惠券
        ll_mine_coupon.setOnClickListener {
            push(ActCons.CouponListActivity, isNeedLogin = true)
        }
        //我的足迹
        ll_mine_footrecords.setOnClickListener {
            push(ActCons.FootActivity, isNeedLogin = true)
        }

    }

    override fun startObserver() {
        mViewModel.showGuessLikeLiveData.observe(this, Observer {
            it?.let {
                if (it.page == 1) {
                    mGuessDatas.clear()
                }
                if (it.data != null) {
                    mineGuessAdapter.addData(it.data!!)
                }
                mDataBinding.autoMine.setEnableLoadMore(it.page < it.sumPage)
            }
            ll_mine_guess_head.visibility = (mGuessDatas.size == 0).judge(View.GONE, View.VISIBLE)
        })
    }

    /**
     * 设置猜你喜欢
     */
    private fun getGuessLike(refresh: Int) {
        mViewModel.loadGuessLike(refresh)

    }


    override fun onRefresh(refreshLayout: RefreshLayout) {
        UserRepository.updateInboxCount()
        getGuessLike(1)
        CountrysRepository.update()
        UserRepository.updateUserInfo()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        getGuessLike(2)
    }

    override val isRegisterEventBus: Boolean
        get() = true

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLoginEvent(event: LoginEvent) {
        UserRepository.getUserInfo().more {
            setUserInfoView()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLogoutEvent(event: LogoutEvent) {
        UserRepository.getUserInfo().more {
            setUserInfoView()
        }
    }
}